package com.qianya.system.manage.web.login.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qianya.model.pojo.login.qo.LoginRoleInsertQO;
import com.qianya.model.pojo.login.qo.LoginRoleQO;
import com.qianya.model.pojo.login.vo.LoginRoleUserVO;
import com.qianya.model.pojo.login.vo.LoginRoleVO;
import com.qianya.model.pojo.login.vo.LoginUsersVO;
import com.qianya.system.manage.web.login.mapper.CustomMapper;
import com.qianya.system.manage.web.login.model.LoginDept;
import com.qianya.system.manage.web.login.model.LoginRole;
import com.qianya.system.manage.web.login.model.LoginUsersPermission;
import com.qianya.system.manage.web.login.model.LoginUsersRolePermission;
import com.qianya.system.manage.web.login.service.ILoginRoleService;
import com.qianya.system.manage.web.login.mapper.LoginRoleMapper;
import com.qianya.system.manage.web.login.service.ILoginUsersPermissionService;
import com.qianya.system.manage.web.login.service.ILoginUsersRolePermissionService;
import org.apache.velocity.util.ArrayListWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.qianya.model.common.CommonResult;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qianya.model.common.ResultCode;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 角色服务实现类
 * </p>
 *
 * @author lhl
 * @since 2020-07-02
 */
@Service
@Transactional
public class LoginRoleServiceImpl extends ServiceImpl<LoginRoleMapper, LoginRole> implements ILoginRoleService {

    @Resource
    private LoginRoleMapper loginRoleMapper;

    @Resource
    private CustomMapper customMapper;
    @Autowired
    private ILoginUsersRolePermissionService usersRolePermissionService;
    @Autowired
    private ILoginUsersPermissionService permissionService;

    /**
     * 查找 角色
     *
     * @author lhl
     * @since 2020-07-02
     */
    @Override
    public CommonResult find(LoginRoleQO loginRoleQO) {

        IPage<LoginRoleVO> iPage = new Page(loginRoleQO.getPageNo(), loginRoleQO.getPageSize());

        iPage = loginRoleMapper.find(iPage, loginRoleQO);

        return CommonResult.success(iPage);
    }

    @Override
    public LoginRoleVO view(String roId) {
        return loginRoleMapper.view(roId);
    }

    @Override
    public CommonResult renewal(LoginRoleInsertQO loginRoleInsertQO) {
        if (StrUtil.isBlank(loginRoleInsertQO.getPermissionId())){
            return CommonResult.error(ResultCode.ERROR, "修改的权限不能为空");
        }
        LoginRole loginRole = new LoginRole();
        BeanUtils.copyProperties(loginRoleInsertQO, loginRole);
        LoginRole one = getOne(new QueryWrapper<LoginRole>().eq("RO_NAME", loginRole.getRoName()).ne("RO_ID", loginRole.getRoId()));
        if(one !=null){
            return CommonResult.error(ResultCode.ERROR, "角色名称已存在，请重新输入");
        }
        String roId = loginRole.getRoId();
        customMapper.deleteRolePermission(roId);
        String[] permissionIds = loginRoleInsertQO.getPermissionId().split(",");
        List<LoginUsersPermission> listRp=permissionService.list(new QueryWrapper<LoginUsersPermission>()
                .in("P_P_ID",permissionIds).eq("P_TYPE",1));
        List<LoginUsersRolePermission> listUrp = new ArrayList<LoginUsersRolePermission>();
        //定义一个空对象
        LoginUsersRolePermission urp = null;
        //遍历
        for (String permissionId : permissionIds) {
            urp = new LoginUsersRolePermission();
            //存入权限ID
            urp.setRPId(permissionId);
            //存入角色ID
            urp.setRRoId(loginRoleInsertQO.getRoId());
            //放入集合
            listUrp.add(urp);
        }
        //放进所有子接口
        for (int i = 0; i <listRp.size() ; i++) {
            urp = new LoginUsersRolePermission();
            //存入权限ID
            urp.setRPId(listRp.get(i).getPId());
            //存入角色ID
            urp.setRRoId(loginRoleInsertQO.getRoId());
            //放入集合
            listUrp.add(urp);
        }
        //判断如果集合非空
        if (!listUrp.isEmpty()) {
            //把集合的数据导入数据库
            usersRolePermissionService.saveBatch(listUrp);
        }
        boolean b = updateById(loginRole);
        if (b) {
            return CommonResult.success("修改成功");
        }
        return CommonResult.error(ResultCode.ERROR, "修改失败");
    }

    /**
     * 新增 角色
     * @author lhl
     * @since 2020-07-02
     */


    /**
     * 修改 角色
     *
     * @author lhl
     * @since 2020-07-02
     */

    @Override
    public CommonResult create(LoginRoleInsertQO loginRoleInsertQO) {
        LoginRole loginRole = new LoginRole();
        //生成角色ID
        String uuid = IdUtil.simpleUUID();
        //设置角色ID
        loginRoleInsertQO.setRoId(uuid);
        BeanUtils.copyProperties(loginRoleInsertQO, loginRole);
        LoginRole ro_name = getOne(new QueryWrapper<LoginRole>().eq("RO_NAME", loginRole.getRoName()));
        if (ro_name != null) {
            return CommonResult.error(ResultCode.ERROR, "角色名称已存在，请重新输入");
        }
        loginRole.setRoCreateTime(new Date());
        //用逗号切割传递过来的权限ID
        if(loginRoleInsertQO.getPermissionId().isEmpty()){
            loginRoleInsertQO.setPermissionId("");
        }
        String[] permissionIds = loginRoleInsertQO.getPermissionId().split(",");
        List<LoginUsersPermission> listRp=permissionService.list(new QueryWrapper<LoginUsersPermission>()
        .in("P_P_ID",permissionIds).eq("P_TYPE",1));
        //新建一个list集合
        List<LoginUsersRolePermission> listUrp = new ArrayList<LoginUsersRolePermission>();
        //定义一个空对象
        LoginUsersRolePermission urp = null;
        //遍历
        for (String permissionId : permissionIds) {
            urp = new LoginUsersRolePermission();
            //存入权限ID
            urp.setRPId(permissionId);
            //存入角色ID
            urp.setRRoId(uuid);
            //放入集合
            listUrp.add(urp);
        }
        //放进所有子接口
        for (int i = 0; i <listRp.size() ; i++) {
            urp = new LoginUsersRolePermission();
            //存入权限ID
            urp.setRPId(listRp.get(i).getPId());
            //存入角色ID
            urp.setRRoId(uuid);
            //放入集合
            listUrp.add(urp);
        }
        //判断如果集合非空
        if (!listUrp.isEmpty()) {
            //把集合的数据导入数据库
            usersRolePermissionService.saveBatch(listUrp);
        }
        boolean b = save(loginRole);
        if (b) {
            return CommonResult.success("添加成功");
        }
        return CommonResult.error(ResultCode.ERROR, "添加失败");
    }


    /**
     * 通过用户id查询角色和权限
     *
     * @param userId
     * @return
     */

    @Override
    public CommonResult findRoleByUserId(String userId) {
        List<LoginRoleVO> roleList = loginRoleMapper.findRoleByUserId(userId);
        return CommonResult.success(roleList);
    }

    @Override
    public CommonResult deleteById(String roId) {
        LoginRole loginRole = loginRoleMapper.selectById(roId);
        Boolean roStatus = loginRole.getRoStatus();
        if (roStatus){
            loginRole.setRoStatus(false);
//            customMapper.deleteRolePermission(roId);
            boolean b = updateById(loginRole);
            if (b) {
                return CommonResult.success("禁用成功");
            } else {
                return CommonResult.error(ResultCode.ERROR, "禁用失败");
            }
        }
        loginRole.setRoStatus(true);
        boolean b = updateById(loginRole);
        if (b) {
            return CommonResult.success("启用成功");
        } else {
            return CommonResult.error(ResultCode.ERROR, "启用失败");
        }
    }

    @Override
    public CommonResult findAllRole() {
        return CommonResult.success(loginRoleMapper.findAllRole());
    }
}
